import React, { useState, useRef, useEffect } from "react";
import _ from 'lodash'
import { Form, Input, Select, Space, Button, DatePicker, Tabs } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { apiMemberGiftIncomeWithdrawalRecordPage, apiMemberGiftIncomeWithdrawalRecord, apiGetTotalAmount } from '@/request/wallet/withdraw.js'
import { getDateTime3 } from '@/utils/getDate'
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import "./style/index.less";
import _connect from '@/_connect'
import { exportSheetTable } from "@/utils/exportTable";
import { apiImPayManageList } from '@/request/wallet/rechargeRecord';

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;
const Item = Form.Item;

const SearchHeader = React.forwardRef((props, ref) => {
  const { getSearchValue, showStatusSelect } = props
  const formRef = useRef()
  const [area, setArea] = useState({})
  const [option, setOption] = useState([])
  useEffect(() => {
    getImPayManageList()
  }, [])
  const getImPayManageList = async () => {
    await apiImPayManageList({}).then(res => {
      if (res.code === 0) {
        let data = []
        res.data.map(item => {
          data.push({
            label: item.accountRemark,
            value: item.id
          })
        })
        setOption(data)
      }
    })
  }
  const onFinish = values => {
    if (!_.isEmpty(values.time)) {
      values.createStartTime = getDateTime3(values.time[0]) + " 00:00:00"
      values.createEndTime = getDateTime3(values.time[1]) + " 23:59:59"
    }
    delete (values.time)
    values = {
      ...values,
      ...area
    }
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getSearchValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      code: '',
      memberInfo: '',
      status: '',
      time: [],
      accountId: null
    })
    getSearchValue({})
  }
  React.useImperativeHandle(ref, () => ({
    reset // 将子组件的 handleClick 方法暴露给父组件
  }));
  return <div className='search-box' style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
    <Form ref={formRef} onFinish={onFinish} layout='inline'>
      <Form.Item name={"memberInfo"} label="会员信息">
        <Input style={{ width: 200 }} suffix={<SearchOutlined />} placeholder={"输入会员ID/会员昵称/会员手机号"} />
      </Form.Item>
      <Form.Item name={"code"} label="提现单号">
        <Input style={{ width: 120 }} placeholder={"输入提现单号"} />
      </Form.Item>
      {showStatusSelect &&
        <Form.Item name={"status"} label="提现状态">
          <Select placeholder="提现状态"
            style={{ width: 100 }}
            options={[
              {
                value: '',
                label: '全部'
              },
              {
                value: '1',
                label: '待审核'
              },
              {
                value: '2',
                label: '被驳回'
              },
              {
                value: '3',
                label: '提现失败'
              },
              {
                value: '4',
                label: '已到账'
              },
            ]} />
        </Form.Item>}
      <Form.Item name={"time"} label="提现时间">
        <RangePicker style={{ width: 240 }} />
      </Form.Item>
      <Form.Item name={"accountId"} label="出款账户">
        <Select placeholder="出款账户"
          style={{ width: 200 }}
          options={option} />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button type='primary' htmlType='submit'>搜索</Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
    </Form>
  </div>
})

class Examine extends React.Component {
  constructor(props) {
    super(props)
    // 创建Ref
    this.childRef = React.createRef();
    this.state = {
      columnsS: [
        {
          title: '提现单号',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '提现流水',
          dataIndex: 'paymentPlatformCode',
          key: 'paymentPlatformCode',
        },
        {
          title: '支付宝单号',
          dataIndex: 'paymentPlatformAlipayCode',
          key: 'paymentPlatformAlipayCode'
        },
        {
          title: '会员ID',
          dataIndex: 'memberId',
          key: 'memberId'
        },
        {
          title: '用户昵称',
          dataIndex: 'memberNickName',
          key: 'memberNickName'
        },
        {
          title: '会员手机号',
          dataIndex: 'memberMobile',
          key: 'memberMobile',
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        },
        {
          title: '提现账户',
          dataIndex: 'withdrawalAccountInfo',
          key: 'withdrawalAccountInfo'
        },
        {
          title: "提现金额",
          dataIndex: 'withdrawalAmount',
          key: 'withdrawalAmount',
          render: text => text && <React.$price price={text} />,
        },
        {
          title: '提现服务费比例',
          dataIndex: 'withdrawalFeeRate',
          key: 'withdrawalFeeRate',
          render: text => text + '%',
        },
        {
          title: "提现手续费",
          dataIndex: "withdrawalFee",
          key: "withdrawalFee",
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "预计到账金额",
          dataIndex: 'amountReceived',
          key: 'amountReceived',
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "提现时间",
          dataIndex: 'createTime',
          key: 'createTime',
        },

        {
          title: "到账时间",
          dataIndex: 'amountReceivedTime',
          key: 'amountReceivedTime',
        },
        {
          title: "提现状态",
          dataIndex: 'status',
          key: 'status',
          render: (text, render) => {
            let txt = ''
            switch (text) {
              // 1待审核 2被驳回 3提现失败 4已到账
              case 1:
                txt = '待审核'
                break;
              case 2:
                txt = '被驳回'
                break;
              case 3:
                txt = '提现失败'
                break;
              case 4:
                txt = '已到账'
                break;
              default:
                break;
            }
            return txt;
          },
        },
        {
          title: "出款账户",
          dataIndex: 'disbursementAccountInfo',
          key: 'disbursementAccountInfo',
        },
        {
          title: "操作",
          fixed: "right",
          render: (text, render) => {
            return (
              <div>
                {render.status == '1' &&
                  <TheButton haspermi={['myPocket:payouts:pass']} onClick={() => this.openThroughDialog(render.withdrawalRecordId)}>通过</TheButton>
                }
                {render.status == '1' &&
                  <TheButton haspermi={['myPocket:payouts:pass']} onClick={() => this.setState({ visible: true, textArea: '', storeId: render.withdrawalRecordId })}>驳回</TheButton>
                }
                <TheButton haspermi={["myPocket:payouts:details"]} onClick={() => this.props.history.push(`/myPocket/userBalance/detail/${render.memberId}`)}>账户明细</TheButton>
              </div>
            );
          },
        },
      ],
      columnsB: [
        {
          title: '提现单号',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '提现流水',
          dataIndex: 'paymentPlatformCode',
          key: 'paymentPlatformCode',
        },
        {
          title: '会员ID',
          dataIndex: 'memberId',
          key: 'memberId'
        },
        {
          title: '用户昵称',
          dataIndex: 'memberNickName',
          key: 'memberNickName'
        },
        {
          title: '会员手机号',
          dataIndex: 'memberMobile',
          key: 'memberMobile',
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        },
        {
          title: '提现账户',
          dataIndex: 'withdrawalAccountInfo',
          key: 'withdrawalAccountInfo'
        },
        {
          title: "提现金额",
          dataIndex: 'withdrawalAmount',
          key: 'withdrawalAmount',
          render: text => text && <React.$price price={text} />,
        },
        {
          title: '提现服务费比例',
          dataIndex: 'withdrawalFeeRate',
          key: 'withdrawalFeeRate',
          render: text => (text) + '%',
        },
        {
          title: "提现手续费",
          dataIndex: "withdrawalFee",
          key: "withdrawalFee",


          render: text => text && <React.$price price={text} />,
        },
        {
          title: "提现时间",
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: "操作",
          fixed: "right",
          render: (text, render) => {
            return (
              <div>
                {render.status == '1' &&
                  <TheButton haspermi={['myPocket:payouts:pass']} onClick={() => this.openThroughDialog(render.withdrawalRecordId)}>通过</TheButton>
                }
                {render.status == '1' &&
                  <TheButton haspermi={['myPocket:payouts:pass']} onClick={() => this.setState({ visible: true, textArea: '', storeId: render.withdrawalRecordId })}>驳回</TheButton>
                }
                <TheButton haspermi={['myPocket:payouts:details']} onClick={() => this.props.history.push(`/myPocket/userBalance/detail/${render.memberId}`)}>账户明细</TheButton>
              </div>
            );
          },
        },
      ],
      dataS: [],
      dataB: [],
      pageDataS: {
        pageNo: 1,
        pageSize: 10,
      },
      totalS: 0,
      rangeS: 1,
      pageDataB: {
        pageNo: 1,
        pageSize: 10,
      },
      totalB: 0,
      rangeB: 1,
      visible: false,
      approvalStatus: 'S',
      exportLoading: false,
      searchValue: {},
      throughVisible: false,
      throughId: '',
      storeId: '',
      reviewTotal: 0,//待审核数量
      showStatusSelect: true,
      textArea: '',
      totalAmount: ""
    };
  }


  async componentDidMount() {
    await this.getData()
    await this.getTotal()//待审核数量

  }
  getTotal = async () => {
    const { approvalStatus, searchValue } = this.state
    let res = await apiMemberGiftIncomeWithdrawalRecordPage({ status: 1 })
    if (res.data && res.code === 0) {
      this.setState({
        reviewTotal: res.totalCount
      })
    }
  }
  getData = async () => {
    let { approvalStatus, searchValue } = this.state
    if (this.state.approvalStatus == 'B') {
      searchValue = {
        ...this.state.searchValue,
        status: 1
      }
    }
    let res = await apiMemberGiftIncomeWithdrawalRecordPage({ ...searchValue, ...this.state[`pageData${approvalStatus}`], })
    if (res.data && res.code === 0) {
      this.setState({
        [`data${approvalStatus}`]: res.data,
        [`pageData${approvalStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${approvalStatus}`]: res.totalCount,
        [`range${approvalStatus}`]: res.totalPage,
      })
    }
    let request = await apiGetTotalAmount({ ...searchValue })
    if (request.code === 0) {
      console.log(request.data);
      this.setState({
        totalAmount: request.data.totalAmountDecimal
      })
    }
  }

  tabChange = (key) => {
    this.childRef.current.reset()
    this.setState({
      showStatusSelect: key !== 'B',
      approvalStatus: key
    }, () => {
      this.getData()
      this.getTotal()//待审核数量
    })
  };
  pageChangeS = (pageNo, pageSize) => {
    this.setState({
      pageDataS: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  pageChangeB = (pageNo, pageSize) => {
    this.setState({
      pageDataB: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })


  };
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageDataS: {
        pageNo: 1,
        pageSize: 10,
      },
      pageDataB: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getTotal()//待审核数量
      this.getData()
    })
  }
  openThroughDialog = id => {
    this.setState({
      throughVisible: true,
      storeId: id
    })
  }
  closeThroughDialog = () => {
    this.setState({
      throughVisible: false,
      storeId: ''
    })
  }
  openRejectedDialog = (storeId) => {
    this.setState({ visible: true, storeId })
  }
  handleCancel = () => {
    this.setState({ visible: false, storeId: '' });
  };
  //驳回
  handleOk = async () => {
    const dismissReason = this.state.textArea
    if (!dismissReason) {
      return React.$message({
        type: 'error',
        content: '请输入驳回原因'
      })
    } else {
      let res = await apiMemberGiftIncomeWithdrawalRecord({ withdrawalRecordId: this.state.storeId, content: dismissReason, type: 2 })
      if (res.code === 0) {
        this.setState({ visible: false }, () => {
          this.getData()
          this.getTotal()//待审核数量
        });
      }
    }
  };

  //表格导出
  async toExportTable() {
    this.setState({ down_loading: true });
    let { searchValue } = this.state
    await apiMemberGiftIncomeWithdrawalRecordPage({ ...searchValue, pageNo: 1, pageSize: -1, })
      .then((res) => {
        if (res.code === 0 && res.data.length > 0) {
          let tH_data = [
            {
              title: "提现列表",
              prop: "",
              children: [
                { prop: 'code', title: '提现单号' },
                { prop: 'paymentPlatformCode', title: '提现流水' },
                { prop: 'paymentPlatformAlipayCode', title: '支付宝单号'},
                { prop: 'memberId', title: '会员ID' },
                { prop: 'memberNickName', title: '用户昵称' },
                { prop: 'memberMobile', title: '会员手机号' },
                { prop: 'withdrawalAccountInfo', title: '提现账户' },
                { prop: 'withdrawalAmount', title: '提现金额', valueType: 'number' },
                { prop: 'withdrawalFeeRate', title: '提现服务费比例' },
                { prop: 'withdrawalFee', title: '提现手续费', valueType: 'number' },
                { prop: 'amountReceived', title: '预计到账金额', valueType: 'number' },
                { prop: 'createTime', title: '提现时间' },
                { prop: 'amountReceivedTime', title: '到账时间' },
                { prop: 'status', title: '提现状态' },
                { prop: 'disbursementAccountInfo', title: '出款账户' },
              ],
            },
          ];
          let tB_data = res.data.map((item) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = item.memberMobile.toString().replace(reg, '$1****$2');
            return {
              code: item.code,
              paymentPlatformCode: item.paymentPlatformCode,
              paymentPlatformAlipayCode: item.paymentPlatformAlipayCode,
              memberId: item.memberId,
              memberNickName: item.memberNickName,
              memberMobile: memberMobile,
              withdrawalAccountInfo: item.withdrawalAccountInfo,
              withdrawalAmount: (item.withdrawalAmount / 100).toFixed(2),
              withdrawalFeeRate: item.withdrawalFeeRate + "%",
              withdrawalFee: (item.withdrawalFee / 100).toFixed(2),
              amountReceived: (item.amountReceived / 100).toFixed(2),
              createTime: item.createTime,
              amountReceivedTime: item.amountReceivedTime,
              status: ["", "待审核", "被驳回", "提现失败", "已到账"][item.status],
              disbursementAccountInfo: item.disbursementAccountInfo,
            };
          });

          this.setState({ down_loading: false });
          exportSheetTable({
            fileName: "提现列表",
            tH_data: tH_data,
            tB_data: tB_data,
            isSheet: true,
            merge: true,
          });
        } else {
          React.$message({
            type: "warning",
            content: "导出操作失败,请重试",
          });
          this.setState({ exportLoading: false });
        }
      })
      .catch((err) => {
        console.log("err:", err);
        React.$message({
          type: "warning",
          content: "导出操作失败,请重试",
        });
        this.setState({ exportLoading: false });
      });
  }
  onFinish = async value => {
    value.storeId = this.state.throughId
    this.setState({ loading: true })
    let res = await apiMemberGiftIncomeWithdrawalRecord({ withdrawalRecordId: this.state.storeId, type: 1 })
    if (res.code === 0) {
      React.$message({
        type: "success",
        content: "操作成功",
      });
      this.setState({
        loading: false,
        throughVisible: false
      }, () => {
        this.closeThroughDialog()
        this.getData()
        this.getTotal()//待审核数量

      })
    } else {
      this.setState({
        loading: false
      })
    }
  }
  /**
* @desc 确认自定义密码验证
* @params Reg {rule} 验证规则
* @params string {value} 需要验证的字符串
* @params fun {callback} 回调函数
* */
  validatePassword = (rule, value, callback) => {
    const password = this.formRef.getFieldsValue(['password']).password;
    if (value !== password) {
      callback('确认两次输入的密码一致')
    }
    callback()
  }
  render() {
    const {
      columnsS,
      columnsB,
      dataS,
      dataB,
      pageDataS,
      pageDataB,
      totalS,
      rangeS,
      totalB,
      rangeB,
      visible,
      loading,
      throughVisible,
      reviewTotal,
      exportLoading,
      approvalStatus,
      showStatusSelect,
      totalAmount
    } = this.state;
    return (
      <div className="p-layout-box commodity-examine">
        <div className="p-search-box" >
          <SearchHeader ref={this.childRef} getSearchValue={this.getValue} showStatusSelect={showStatusSelect} />
          {approvalStatus == 'S' && <TheButton
            size="middle"
            type="default"
            haspermi={["myPocket:payouts:export"]}
            onClick={() => this.toExportTable()}
            loading={exportLoading}
          >
            导出
          </TheButton>}
        </div>
        <Tabs defaultActiveKey="S" onChange={this.tabChange}>
          <TabPane tab="提现列表" key="S">
            {/* <div className="p-layout-content-pagination"> */}
            <TheTable
              scroll={{ x: "max-content", y: '63vh' }}
              columns={columnsS}
              dataSource={dataS}
            />
            <span style={{ float: "left", position: "relative", bottom: "-20px", fontSize: "20px", fontWeight: "600" }} >提现金额合计（元）：{totalAmount}</span>
            <ThePagination
              pageNo={pageDataS.pageNo}
              pageSize={pageDataS.pageSize}
              total={totalS}
              pageChange={this.pageChangeS}
              showTotal={() => `共${rangeS}页/${totalS}条数据`}
            />
            {/* </div> */}
          </TabPane>
          <TabPane tab={"待审核列表（" + reviewTotal + "）"} key="B">
            {/* <div className="p-layout-content-pagination"> */}
            <TheTable
              scroll={{ x: "max-content" }}
              columns={columnsB}
              dataSource={dataB}
            />
            <span style={{ float: "left", position: "relative", bottom: "-20px", fontSize: "20px", fontWeight: "600" }} >提现金额合计（元）：{totalAmount}</span>
            <ThePagination
              pageNo={pageDataB.pageNo}
              pageSize={pageDataB.pageSize}
              total={totalB}
              pageChange={this.pageChangeB}
              showTotal={() => `共${rangeB}页/${totalB}条数据`}
            />
            {/* </div> */}
          </TabPane>
        </Tabs>
        <TheDialog
          title="通过提现"
          width={400}
          visible={throughVisible}
          handleCancel={this.closeThroughDialog}
          footer={null}
        >
          <div style={{ margin: '30px 0' }}>通过后，将自动给用户打款</div>
          <div className="p-text-align">
            <Space size="large">
              <Button key="back" onClick={this.closeThroughDialog}>
                取 消
              </Button>
              <Button type="primary" loading={loading} htmlType="primary" onClick={this.onFinish}>
                确认通过
              </Button>
            </Space>
          </div>
        </TheDialog>
        <TheDialog
          title="输入驳回原因"
          width={400}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <TextArea
            onChange={(e) => this.setState({
              textArea: e.target.value
            })}
            allowClear
            autoSize={{ minRows: 6, maxRows: 6 }}
            maxLength={200}
            showCount
          />
        </TheDialog>
      </div>
    );
  }
}

export default Examine;
